/*
 * @Author: sjf 1758142861@qq.com
 * @Date: 2023-03-22 16:09:05
 * @LastEditors: sjf 1758142861@qq.com
 * @LastEditTime: 2023-03-22 17:04:10
 * @FilePath: /D_C_lib/thread_safety/pthread_mutex_init.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<unistd.h>
#include<pthread.h>

//动态创建
pthread_mutex_t mutex;
int ticket = 1000;
void* _start_routine(void* args)
{
    const char* name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            usleep(1234);
            std::cout << "name:" << name <<"get a ticket:" << ticket--
             << std::endl; 
             pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            std::cout << "ticket < 0" << std::endl;
            break;
        }
    }
    std::cout << name << ":quit" << std::endl;
    return nullptr;
    //pthread_exit((void*)0);
}

int main()
{
    pthread_mutex_init(&mutex,nullptr);
    pthread_t tid1,tid2,tid3,tid4;
    pthread_create(&tid1,nullptr,_start_routine,(void*)"thread 1");
    pthread_create(&tid2,nullptr,_start_routine,(void*)"thread 2");
    pthread_create(&tid3,nullptr,_start_routine,(void*)"thread 3");
    pthread_create(&tid4,nullptr,_start_routine,(void*)"thread 4");

    pthread_join(tid1,nullptr);
    pthread_join(tid2,nullptr);
    pthread_join(tid3,nullptr);
    pthread_join(tid4,nullptr);

    pthread_mutex_destroy(&mutex);
    return 0;
}